/**
 * 系统后台数据源配置JS-systemDataConfig.jsp
 */

//项目路径
var strPath = window.document.location.pathname;
//var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
var postPath = "/gdp";

$(document).ready(function(){
	//左侧tree数据绑定
	var setting = {	
		data: {
			key:{
				title:"hint"
			},
			simpleData: {
				enable: true
			}
		},
		callback: {
			onClick: onClick
		}
	};
	var zNodes =GetLeftTreeData();
	$.fn.zTree.init($("#tree"), setting, zNodes);
	
	
	
	//表信息配置-保存
	$("#btn_tableSave").click(function(){
		var validresult = validTableInfo();
		var saveUrl="";
		if($("#hid_IsMark").val() == "2"){
			saveUrl=postPath + '/system/singleReport/updateExtrepByGuid';
		}else{
			saveUrl=postPath + '/system/singleReport/insertExtrep';
		}
		
		if(validresult){
		    var checField=new Array();
  		    $("input[name='fields']:checked").each(function(){
  		    	checField.push($(this).val());
  		    });
			var pp ={
					guid:$("#guid").val(),
					servicename:$("#servicename").val(),
					tempid:$("#tempid").val(),
					rtitle:$("#rtitle").val(),
					remark:$("#remark").val(),
					dtDbKey:$("#dtDbKey").val(),
					dtConfigId:$("#dtConfigId").val(),
					fields:checField.toString(),
					//guid:$("#hid_dtguid").val()
			}
			 $.ajax({
                 type : 'POST',
                 url : saveUrl,
                 async : false,
                 data : JSON.stringify(pp),
                 dataType : 'json',
                 contentType:"application/json",
                 success : function(res) {
                	 if(res >0)
                	 {
                	 	showMsg("保存成功!","success");
                		 $("#hid_dtConfigId").val($("#dtConfigId").val());
                		 zNodes =GetLeftTreeData();
                		 $.fn.zTree.init($("#tree"), setting, zNodes);
                	 }else{
						 showMsg("保存失败,请刷新后重试!","error");
                	 }
                 }
             });
		}
			
	});
	
	//装载下拉框（模板，数据库，表）
	bingReportTemplate();
	bingDataBase();
	$("#dtDbKey").on("change",bingDataTable);
	$("#dtConfigId").on("change",bingShowColumn);
	//$("#btn_propertySave").on("click",insertRepconfig);
	//bingDataTable();


	//Tree点击事件
	function onClick(event, treeId, treeNode, clickFlag) {
		cleanTableInfo();
		$('#myTab a[href="#tab_1_1_1"]').tab('show')
		$("#hid_IsMark").val(treeNode.isMark);
		if(treeNode.isMark == "1"){//新增数据表
			$("#dtDbKey").val(treeNode.id);
			bingDataTable();
		}else if(treeNode.isMark == "2"){//修改数据表
			var cfgExtrep="";
			$.ajax({
		        type : 'POST',
		        url : postPath + '/system/singleReport/getcfgExtrepByGuid',
		        data:{guid:treeNode.id},
		        async : false,
		        success : function(res) {
		        	cfgExtrep=res;
		        }
		    });
			//bingDataTable(cfgExtrep.dtConn);
			$("#guid").val(cfgExtrep.guid);
			$("#servicename").val(cfgExtrep.servicename);
			$("#tempid").val(cfgExtrep.tempid);
			$("#rtitle").val(cfgExtrep.rtitle);
			$("#remark").val(cfgExtrep.remark);
			$("#dtDbKey").val(cfgExtrep.dtDbKey);
			bingDataTable();
			$("#dtConfigId").val(cfgExtrep.dtConfigId);
			//$("#hid_dtguid").val(cfgtable.guid);
			$("#hid_dtConfigId").val(cfgExtrep.dtConfigId);
			$("#guid").attr("disabled","disabled");
			//$("#dtConfigId").attr("disabled","disabled");
			bingShowColumn();
			var checValue=cfgExtrep.fields;
			$("input[name='fields']").each(function(){
				if(null != checValue && checValue.indexOf(this.value) >= 0){
					this.checked=true;
				}
			});
			
		}
		
		
	}
	
	//获取左侧列表数据
	function GetLeftTreeData()
	{
		var treeData;
		$.ajax({
	        type : 'POST',
	        url : postPath + '/system/singleReport/treeList',
	        async : false,
	        success : function(res) {
	        	treeData=res;
	        }
	    });
		return treeData;
	}
	
	//左侧树刷新操作
	$("#tree_refresh").click(function(){
		zNodes =GetLeftTreeData();
		$.fn.zTree.init($("#tree"), setting, zNodes);
	});

	//左侧树删除操作
	$("#tree_del").click(function(){
		if($("#guid").val() == ""){
			bootbox.alert("请选择要删除的报表");
			return;
		}
		bootbox.confirm("确认删除?", function(result) {
			if(result == false){
				return;
			}
			 $.ajax({
	                url:  postPath + '/system/singleReport/delExtrepByGuid',
	                type: 'POST',
	                data: { guid: $("#guid").val() },
	                success: function (data) {
	                	if(data == true){
							showMsg("删除成功!","success");
	                		zNodes =GetLeftTreeData();
		                    $.fn.zTree.init($("#tree"), setting, zNodes);
	                	}else{
							showMsg("删除失败,请刷新后重试!","error");
	                	}
	                    
	                },
	                error:function()
	                {
						showMsg("删除失败,请刷新后重试!","error");
	                }
	            });
	     }); 
	});
	/*****************************Begin表信息配置*********************/
	
	//获取报表模板
	function bingReportTemplate(){
		var strTabletxt="<option selected='selected' value=''>请选择表模板</option>";
		$("#tempid").empty();
		$.ajax({
			type: 'POST',
			url:postPath+'/system/reptemplet/selectReptempletList',
			data:"",
			async:false,
			success:function(data){
				$.each(data,function(i,e){
					var strtxt = "<option value="+e.guid+">"+e.name;
					strtxt+="</option>";
					strTabletxt+=strtxt;
				});
				$("#tempid").html(strTabletxt);
			}
			
		});
	}
	//获取所属库
	function bingDataBase(){
		var strTabletxt="<option selected='selected' value=''>请选择数据库</option>";
		$("#dtDbKey").empty();
		$.ajax({
			type: 'POST',
			url:postPath+'/system/singleReport/getCfgDBList',
			data:"",
			async:false,
			success:function(data){
				$.each(data,function(i,e){
					var strtxt = "<option value=" + e.dbKey + ">" + e.dbName;
					if(e.dbMark !=null && e.dbMark !="" && e.dbMark !="undefined"){
						strtxt+="("+e.dbMark+")";
					}
					strtxt+="</option>";
					strTabletxt+=strtxt;
				});
				$("#dtDbKey").html(strTabletxt);
			}
			
		});
	}
	//获取所属表
	function bingDataTable(){
		var db = $("#dtDbKey").val();
		var strTabletxt="<option selected='selected' value=''>请选择数据表</option>";
		$("#dtConfigId").empty();
		$.ajax({
			type: 'POST',
			url:postPath+'/system/singleReport/getCfgTableListByDb',
			data:{dtconn:db},
			async:false,
			success:function(data){
				$.each(data,function(i,e){
					var strtxt = "<option value="+e.dtConfigId+">"+e.dtName;
					if(e.dtNameCn !=null && e.dtNameCn !="" && e.dtNameCn !="undefined"){
						strtxt+="("+e.dtNameCn+")";
					}
					strtxt+="</option>";
					strTabletxt+=strtxt;
				});
				$("#dtConfigId").html(strTabletxt);
			}
			
		});
	}
	
	function bingShowColumn() {
		var table = $("#dtConfigId").val();
		$("#toColumn").empty();
		var strTabletxt="";
		$.ajax({
			type: 'POST',
			url:postPath+'/system/singleReport/getCfgFieldListBytable',
			data:{dtConfigId:table},
			async:false,
			success:function(data){
				$.each(data,function(i,e){
					var strtxt = "<label><input type='checkbox' name='fields' value='" + e.dfName + "' class='icheck'>  " + e.dfNameCn + "  </label>";
					strTabletxt+=strtxt;
				});
				$("#toColumn").html(strTabletxt);
			}
			
		});
	}
	
	//表信息配置-选择数据表
	$("#dtName").click(function(){
		$.ajax({
			type:'POST',
			url:postPath + '/system/dataConfig/parmaryKey',
			data:{dbkey:$("#dtConn").val(),dtname:$("#dtName").val()},
			success:function(data){
				$("#dtOrder").val(data);
				$("#dtPrimarykey").val(data);
			}
		});
	});
	
	
	//表信息配置-验证
	function validTableInfo()
	{	
		if($("#servicename").val() ==""){
			$("#valide_dtMessage").html("报表名称不能为空,请选择!");
			return false;
		}else{
			$("#valide_dtMessage").html("");
		}
		
		if($("#guid").val() == ""){
			$("#valide_dtMessage").html("报表标识不能为空,请输入!");
			return false;
		}else{
			if($("#hid_IsMark").val() != "2"){
				var dtConfignum=true;
				$.ajax({
					type:'POST',
					url:postPath + '/system/singleReport/getExtrepGuid',
					data:{guid:$("#guid").val()},
					async:false,
					success:function(num){
						dtConfignum=num;
					}
				});
				if(!dtConfignum){
					$("#valide_dtMessage").html("表标识已存在，请重新输入!");
					return false;
				}else{
					$("#valide_dtMessage").html("");
				}
			}else{
				$("#valide_dtMessage").html("");
			}
		}
		
		if($("#tempid").val() == ""){
			$("#valide_dtMessage").html("请选择报表模板!");
			return false;
		}else{
			$("#valide_dtMessage").html("");
		}
		
		if($("#rtitle").val() == ""){
			$("#valide_dtMessage").html("请输入模板标题!");
			return false;
		}else{
			$("#valide_dtMessage").html("");
		}
		
		if($("#dtDbKey").val() == ""){
			$("#valide_dtMessage").html("请选择所属库!");
			return false;
		}else{
			$("#valide_dtMessage").html("");
		}
		
		if($("#dtConfigId").val() == ""){
			$("#valide_dtMessage").html("请选择所属表!");
			return false;
		}else{
			$("#valide_dtMessage").html("");
		}
		return true;
	}
	
	//表信息配置-清空信息
	function cleanTableInfo()
	{
		$("#servicename").val("");
		$("#tempid").val("");
		$("#dtDbKey").val("");
		$("#dtConfigId").val("");
		$("#rtitle").val("");
		$("#remark").val("");
		$("#guid").val("");
		$("#hid_IsMark").val("");
		//$("#hid_dtguid").val("");
		$("#hid_dtConfigId").val("");
		//$("#dtName").removeAttr("disabled");
		$("#guid").removeAttr("disabled");
		$("#toColumn").empty();
	}
	/*****************************End表信息配置*********************/
	
	/*****************************Begin字段配置*********************/
	//字段配置tab
	$("#a_tab_field").click(function(){
		var dtConfigId=$("#hid_dtConfigId").val();
		if(dtConfigId == ""){
			bootbox.alert("请先设置报表服务信息!");
			return;
		}
		$("#tb_fieldList").bootstrapTable('refresh');
		getFieldList();		
	});

	//字段配置-获取字段列表
	function getFieldList(){
		$("#tb_fieldList").bootstrapTable({
			url : postPath + '/system/singleReport/getAllRepconfig',
		    undefinedText : '-',
		    striped : true, // 是否显示行间隔色  
		    cache : false, // 是否使用缓存  
		    queryParams : queryFieldParams, 
		    uniqueId : "guid", // 每一行的唯一标识 
		    columns:[{
		    	field : 'state',  
		        checkbox : true,  
		        align : 'center',  
		        valign : 'middle'
		    },{
		    	title : '服务标识',  
		        field : 'rguid',  
		        align : 'center', 
		        valign : 'middle'
		    },{
		    	title : '服务属性',  
		        field : 'propname',  
		        align : 'center', 
		        valign : 'middle',
		        //editable: true
		    },{
		    	title : '属性名称',  
		        field : 'propcaption',  
		        align : 'center', 
		        valign : 'middle',
		        //editable: true
		    },{
		    	title : '模板属性值',  
		        field : 'propvalue',  
		        align : 'center', 
		        valign : 'middle',
		        editable: true
		    }],
		    onEditableSave:function (field, row, oldValue, $el){
		    	var baseRepconfig ={
						"guid":row.guid,
						"propvalue":row.propvalue
				};
				
				 $.ajax({
	                 type : 'POST',
	                 url :  postPath + '/system/singleReport/updateRepconfigProp',
	                 async : false,
	                 data : JSON.stringify(baseRepconfig),
	                 dataType : 'json',
	                 contentType:"application/json",
	                 success : function(res) {
	                	 if(res >0)
	                	 {
							 showMsg("修改成功!","success");
	 	                    $('#tb_fieldList').bootstrapTable('refresh');
	                	 }else{
							 showMsg("修改失败,请刷新后重试!","error");
	                	 }
	                 }
	             });
		    }
		});
	}
	
	//字段配置-字段列表参数
	function queryFieldParams(pageReqeust) {  
	    var temp = {
	    		rguid:$("#guid").val()
	    };
	    return temp;
	} 
	//字段配置-新增字段
	$("#btn_fieldAdd").click(function(){
		$("#fieldIframe").empty();
		var strc = "";
		$.ajax({
			type: 'POST',
			url:postPath+'/system/singleReport/getRepaddonsCheck',
			data:{rguid:$("#guid").val(),tempId:$("#tempid").val()},
			async:false,
			success:function(data){
				$.each(data,function(i,e){
					strc+="<div class='form-group'>";
					strc+="<label class='col-md-4 control-label'>&nbsp;&nbsp;" + e.propcaption + ":</label>";
					strc+="<div class='col-md-8'>";
					strc+="<input id='"+ e.guid +"' name='"+ e.guid +"' type='text' class='form-control input-inline input-medium input-circle' placeholder='请输入"+ e.propcaption +"' >";
					strc+="</div>";
					strc+="</div>";
					strc+="<hr>";
				});
				strc+="<button id='btn_propertySave'onclick='insertRepconfig();' type='button' class='btn blue'>保&nbsp;&nbsp;存</button>";
				$("#fieldIframe").html(strc);
				//$("#btn_propertySave").on("click",insertRepconfig);
			}
			
		});
        //$("#fieldIframe").attr("src", frameSrc);
        $("#FieldModul").modal('show');
	});
	
	
	//字段配置-新增字段Modul关闭监听事件
	$("#FieldModul").on('hidden.bs.modal', function (e) {
		$("#tb_fieldList").bootstrapTable('refresh');
    });
	
	//字段配置-删除字段
	$("#btn_fieldDel").click(function(){
		var row = $('#tb_fieldList').bootstrapTable('getSelections');
        if (row == null || row == "") {
            bootbox.alert("请选择一行!");
            return;
        }
        bootbox.confirm("确认删除?", function(result) {
			if(result == false)
				return;
			var guids="";
			$.each(row,function(i,e){
				guids+=e.guid+",";
			});
			guids = guids.substring(0,guids.length-1);
			 $.ajax({
	                url:  postPath + '/system/singleReport/deleteRepconfigProp',
	                type: 'POST',
	                data: { guids: guids },
	                success: function (data) {
						showMsg("删除成功!","success");
	                    $('#tb_fieldList').bootstrapTable('refresh');
	                },
	                error:function()
	                {
						showMsg("删除失败!","error");
	                }
	            });
         }); 
        
        
	});
	
	/*****************************End字段配置*********************/
	
	/*****************************Begin数据预览*********************/
	//数据预览tab
	$("#a_tab_view").click(function(){
		var dtConfigId=$("#hid_dtConfigId").val();
		if(dtConfigId == ""){
			bootbox.alert("请先设置表信息!");
			return;
		}
		$("#tb_viewList").bootstrapTable('refresh');
		dataView();
	});
	
	//数据预览-生成表格
	function dataView(){
		var columns = [];
   		//数据预览-创建表格
		$.ajax({
            url:  postPath + '/system/dataConfig/getAllField',
            type: 'POST',
            async:false,
            data: { dtConfigId:$("#hid_dtConfigId").val(),num:Math.random() },
            success: function (data) {
            	$.each(data,function(i,e){
            		columns.push({ "field": e.dfName, "title": e.dfNameCn, "align": 'center', "valign": 'middle' });
            	});
            },
            error:function()
            {
				showMsg("数据加载失败!","error");
            }
        });
		
	   	//数据列表
		$("#tb_viewList").bootstrapTable('destroy').bootstrapTable({  
		    url : postPath + '/system/dataConfig/viewData',
		    undefinedText : '-',  
		    pagination : true, // 分页  
		    striped : true, // 是否显示行间隔色  
		    queryParams : queryViewParams,  
		    cache : false, // 是否使用缓存  
		    pageList : [ 5, 10, 20 ],  
		    toolbar : "",// 指定工具栏  
		    showColumns : false, // 显示隐藏列  
		    showRefresh : false, // 显示刷新按钮  
		    uniqueId : "dbKey", // 每一行的唯一标识  
		    sidePagination : "server", // 服务端处理分页  
		    columns : columns
		});
	}
	
	/**查询条件与分页数据 */  
	function queryViewParams(pageReqeust) {  
	    var temp = {
	        order: pageReqeust.order,
	        pageNo: pageReqeust.offset/pageReqeust.limit+1,
	        pageSize: pageReqeust.limit,
	        dtConfigId:$("#hid_dtConfigId").val()
	    };
	    return temp;
	} 
	/*****************************End数据预览*********************/
});	

function insertRepconfig(){
	var strprop = "{";
	$("#fieldIframe input[type='text']").each(function(index,item){
		if(null != $(this).val() && "" != $(this).val()) {
			strprop+='"' + $(this).attr('name') +'"' +":" + '"' +$(this).val() + '"' +",";
		}
	});
	strprop+="}";
	$.ajax({
        url:  postPath + '/system/singleReport/insertRepcofig',
        type: 'POST',
        data: { strFields: strprop,rguid: $("#guid").val(), },
        success: function (data) {
			showMsg("新增成功!","success");
            $('#tb_fieldList').bootstrapTable('refresh');
            $("#FieldModul").modal('hide');
        },
        error:function()
        {
			showMsg("新增失败,请重试!","error");
        }
    });
};

function showMsg(text, icon) {
	$.toast().reset('all');
	$.toast({
		text: text,
		icon: icon,
		showHideTransition: 'fade',
		allowToastClose: true,
		hideAfter: 1500,
		stack: false,
		position: 'top-right',
		textAlign: 'left',
		loader: true,
		loaderBg: '#9ec600',
	});
}
